﻿using System;

namespace SQLLink.DomainClasses
{
    public class LatLon
    {
        private const double MinutesToDegrees = 1.0 / 60.0; // Minutes to degrees converter
        private const int precision = 5;                    // Precision of the LatLon object latitude and longitude
        public double Latitude { get; set; }    // Latitude value    
        public double Longitude { get; set; }   // Longitude value
 
        // General constructor
        public LatLon()
        {
        }

        /// <summary>
        /// Specific constructor allowing to create a latlon object when know latitude and longitude
        /// </summary>
        /// <param name="iLatitude">Latitude of the LatLon object</param>
        /// <param name="iLongitude">Longitude of the LatLon object</param>
        public LatLon(double iLatitude, double iLongitude)
        {
            Latitude = iLatitude;
            Longitude = iLongitude;
        }

        public LatLon(string location)
        {
            var ggm = new GGM();
            var GoogleGeocodeMatrix = ggm.GetLatLon(location);
            Latitude = GoogleGeocodeMatrix.Latitude;
            Longitude = GoogleGeocodeMatrix.Longitude;
        }

        public LatLon(GPRMC Gprmc)
        {
            // Gets the degree value of lat and lon
            var latDegrees = Gprmc.Latitude < 0 ? Math.Ceiling(Gprmc.Latitude / 100) : Math.Floor(Gprmc.Latitude / 100);
            var lonDegrees = Gprmc.Longitude < 0 ? Math.Ceiling(Gprmc.Longitude / 100) : Math.Floor(Gprmc.Longitude / 100);

            // Gets the minute value of lat an lon
            var latMinutes = (Gprmc.Latitude / 100 % 1) * 100 * MinutesToDegrees;
            var lonMinutes = (Gprmc.Longitude / 100 % 1) * 100 * MinutesToDegrees;

            // Round the value to a constant precision
            Latitude = Math.Round(latDegrees + latMinutes, precision);
            Longitude = Math.Round(lonDegrees + lonMinutes, precision);
        }

        /// <summary>
        /// This method returns a string representing the latlon
        /// </summary>
        /// <returns>string representing the latlon</returns>
        public override string ToString()
        {
            return Latitude.ToString().Replace(',', '.')+ "," + Longitude.ToString().Replace(',', '.');
        }
    }
}
